package com.framework.config;

import com.framework.exception.RRException;
import com.framework.exception.menu.RespCode;
import com.framework.exception.util.RespResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.validation.ConstraintViolationException;

/**
 * 功能描述: 全局自定义异常处理
 *
 * @author ck
 * @date 2018/8/22 13:57
 */
@RestControllerAdvice
public class RRExceptionHandler {
	private Logger logger = LoggerFactory.getLogger(getClass());


	@ExceptionHandler(RRException.class)
	public RespResult handleRRException(RRException e) {
		RespResult r = new RespResult();
		r.put("code", e.getCode());
		r.put("msg", e.getMessage());
		return r;
	}

	@ExceptionHandler(value = { ConstraintViolationException.class })
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public RespResult handleConstraintViolationException(ConstraintViolationException e) {
		logger.error(e.getMessage(), e);
		return RespResult.error("500",e.getMessage());
	}

	@ExceptionHandler(value = { IllegalArgumentException.class })
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public RespResult handleIllegalArgumentException(IllegalArgumentException e) {
		logger.error(e.getMessage(), e);
		return RespResult.error("501",e.getMessage());
	}

	@ExceptionHandler(value = { NoHandlerFoundException.class })
	@ResponseStatus(HttpStatus.NOT_FOUND)
	public RespResult handleNoHandlerFoundException(NoHandlerFoundException e) {
		logger.error(e.getMessage(), e);
		return RespResult.error("404",e.getMessage());
	}

	@ExceptionHandler(DuplicateKeyException.class)
	public RespResult handleDuplicateKeyException(DuplicateKeyException e) {
		logger.error(e.getMessage(), e);
		return RespResult.error("数据库中已存在该记录");
	}

	@ExceptionHandler(Exception.class)
	public RespResult handleException(Exception e) {
		logger.error(e.getMessage(), e);
		return RespResult.error("9999",e.getMessage());
	}
}
